import logging

import requests

# 生成日志对象
logger = logging.getLogger(__name__)

class RequestUtil:
    """HTTP请求工具类，处理认证和请求发送"""

    # 类变量，全局共享
    session = None
    token = None

    @classmethod
    def init_session(cls):
        """初始化session"""
        if cls.session is None:
            cls.session = requests.Session()
        return cls.session

    @classmethod
    def get_token(cls):
        """获取认证token"""
        if cls.token is None:
            cls.generate_token()
        return cls.token

    @classmethod
    def generate_token(cls):
        """生成认证token"""
        session = cls.init_session()
        url = "http://localhost:8888/api/private/v1/login"
        data = {"username": "admin", "password": "123456"}

        response = session.post(url=url, data=data)
        res_data = response.json()

        # 确保token格式正确
        cls.token = res_data['data']['token']
        return cls.token

    @classmethod
    def send_all_request(cls, **kwargs):
        """发送HTTP请求，自动添加认证头"""
        # 确保session和token已初始化
        if cls.session is None:
            cls.init_session()
        if cls.token is None:
            cls.generate_token()

        # 提取并处理variables参数
        variables = kwargs.pop("variables", {})
        if variables:
            print(f"接收到的variables参数: {variables}")  # 添加调试输出

            # 处理URL中的变量替换
            url = kwargs.get("url", "")
            print(f"原始URL: {url}")  # 添加调试输出

            for key, value in variables.items():
                if isinstance(value, bool):
                    value = int(value)
                placeholder = f"${{{key}}}"
                print(f"尝试替换: {placeholder} → {value}")  # 添加调试输出
                url = url.replace(placeholder, str(value))
                print(f"替换后URL: {url}")  # 添加调试输出

            kwargs["url"] = url
            print(f"最终处理后的URL: {url}")  # 添加调试输出

        # 添加认证头
        headers = kwargs.pop("headers", {})
        headers["Authorization"] = cls.token
        kwargs["headers"] = headers

        # 处理文件上传
        files = kwargs.pop("files", {})
        opened_files = {}

        try:
            # 打开文件
            for file_key, file_value in files.items():
                if isinstance(file_value, str):
                    opened_files[file_key] = open(file_value, 'rb')
                else:
                    # 已经是文件对象，直接使用
                    opened_files[file_key] = file_value

            # 如果有文件，添加到kwargs
            if opened_files:
                kwargs["files"] = opened_files

            # 打印请求四要素日志
            for key, value in kwargs.items():
                logger.info(f"请求：{key} 参数: {value}")

            # 发送请求
            response = cls.session.request(**kwargs)

            # 请求结果（响应数据）打印到日志
            # 判断返回的内容是否为json格式
            if "json" in response.headers.get("content-type"):
                logger.info("响应数据：%s" %response.json())
            else:
                logger.info("响应内容太长，不显示在日志\n")
            return response

        except requests.exceptions.RequestException as e:
            # 处理请求异常
            print(f"请求失败: {str(e)}")
            raise
        except Exception as e:
            # 处理其他异常
            print(f"发生未知错误: {str(e)}")
            raise
        finally:
            # 确保所有打开的文件都被关闭
            for file_obj in opened_files.values():
                if hasattr(file_obj, 'close'):
                    file_obj.close()

    @classmethod
    def reset(cls):
        """重置session和token"""
        if cls.session:
            cls.session.close()
            cls.session = None
        cls.token = None
